import { Models } from '../../../../common/typings/model'
import { User } from '../../../../common/typings/user'
import KoaRouter from 'koa-router'
import Mysql from '../../../../core/Mysql'
import httpErrors from '../../../../core/HttpException'
import validator from '../../../../middlewares/validator'
import Auth from '../../../../middlewares/Auth'
import editUserInfo from '../../../../common/apiValidate/system/user/editUserInfo'
import Config from '../../../../config/Config'
import { Menu } from '../../../../common/typings/menu'
const router = new KoaRouter({
  prefix: `${Config.api_prefix}system/user`,
})

interface Permissions {
  name: string
  roleId: number
  id: number
  menuType: Menu.MenuType
  show: number
  actions: User.Action[]
  parentId: number
  serialNum: number
  permission: string
}
/**
 * 获取用户详情
 */
router.get('/query', Auth.verifyTokenPermission, async (ctx: Models.Ctx) => {
  const id = ctx.auth.uid as number
  // roleId 字段，角色，与权限相关
  const res = await Mysql.command(`
        SELECT
            user.user_name,
            user.email,
            user.info infoStr,
            user.deleted,
            role.NAME roleName,
            role.id roleId,
            role.permissions,
            menu.label menuLabel,
            menu.id menuId,
            menu.type menuType,
            menu.show menuShow,
            menu.serial_num,
            menu.parent_id menuParentId,
            menu.permission menuPermission
        FROM
            user,
            role,
            menu
        WHERE
            user.id = ${id}
            AND user.role_id = role.id
            AND FIND_IN_SET(menu.id , role.permissions)
    `)
  const list = (res.results as User.User[]).map((item) => {
    item.info = JSON.parse(item.infoStr)
    return {
      ...item,
    }
  })
  const newList: User.User[] = []
  list.forEach((element: User.User) => {
    const info: User.UserInfo = JSON.parse(element.infoStr)
    const data = newList.find(
      (item) => info.nickName === item.info.nickName && element.roleId === item.roleId && element.menuId === item.menuId
    )
    if (!data) {
      newList.push(element)
      // element.actions = [
      //     {
      //         actionEnName: element.actionEnName,
      //         actionLabel: element.actionLabel,
      //         defaultCheck: element.defaultCheck,
      //     }
      // ]
    } else {
      // data.actions.push({
      //     actionEnName: element.actionEnName,
      //     actionLabel: element.actionLabel,
      //     defaultCheck: element.defaultCheck,
      // })
    }
  })
  const { info, roleName, menuId, menuLabel, userName, roleId, email } = list[0]

  const allPermissions: Permissions[] = newList.map((item) => {
    // const actionList = JSON.parse(item.actionCheck)
    // console.log(JSON.parse(actionList))
    return {
      roleId: item.roleId,
      roleName: item.roleName,
      id: item.menuId,
      menuType: item.menuType,
      name: item.menuLabel,
      show: item.menuShow,
      serialNum: item.serialNum,
      actions: [],
      parentId: item.menuParentId,
      permission: item.menuPermission,
    }
  })
  const allActions: Permissions[] = allPermissions.filter((item) => item.menuType === 3)
  const allMenu: Permissions[] = allPermissions.filter((item) => item.menuType === 1 || item.menuType === 2) || []
  allMenu.forEach((menu) => {
    menu.actions = allActions
      .filter((item) => item.parentId === menu.id)
      .map((item) => {
        return {
          id: item.id,
          serialNum: item.serialNum,
          permission: item.permission,
        }
      })
  })
  const userInfo = {
    userName,
    email,
    info,
    role: {
      roleName,
      menuId: 0,
      roleId,
      menuLabel: '系统',
      permissions: allMenu,
    },
  }
  throw new httpErrors.Success(userInfo)
})

export default router
